package com.shxzz.easy12306.services.ticket.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shxzz.easy12306.framework.starter.cache.StringRedisTemplateProxy;
import com.shxzz.easy12306.framework.starter.cache.toolkit.CacheUtil;
import com.shxzz.easy12306.services.ticket.common.constant.RedisKeyConstant;
import com.shxzz.easy12306.services.ticket.common.constant.TicketConstant;
import com.shxzz.easy12306.services.ticket.dao.entity.TrainStationPriceDO;
import com.shxzz.easy12306.services.ticket.dao.mapper.TrainStationPriceMapper;
import com.shxzz.easy12306.services.ticket.service.TrainStationPriceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 火车价格信息服务层接口
 *
 * @author shxzz
 * @create 2024-03-09-15:25
 */
@RequiredArgsConstructor
@Service
public class TrainStationPriceServiceImpl implements TrainStationPriceService {

    private final StringRedisTemplateProxy stringRedisTemplateProxy;

    private final TrainStationPriceMapper trainStationPriceMapper;

    @Override
    public List<TrainStationPriceDO> getTrainStationPrice(String trainId, String departure, String arrival) {
        String trainPriceInfo = stringRedisTemplateProxy.safeGet(
                CacheUtil.buildKey(RedisKeyConstant.TRAIN_STATION_PRICE_PREFIX, trainId, departure, arrival),
                String.class,
                () -> {
                    LambdaQueryWrapper<TrainStationPriceDO> queryWrapper = Wrappers.lambdaQuery(TrainStationPriceDO.class)
                            .eq(TrainStationPriceDO::getTrainId, trainId)
                            .eq(TrainStationPriceDO::getDeparture, departure)
                            .eq(TrainStationPriceDO::getArrival, arrival)
                            .select(TrainStationPriceDO::getSeatType, TrainStationPriceDO::getPrice);
                    List<TrainStationPriceDO> trainStationPriceDOS = trainStationPriceMapper.selectList(queryWrapper);
                    return JSON.toJSONString(trainStationPriceDOS);
                },
                TicketConstant.ADVANCED_QUERY_TICKET_DAY,
                TimeUnit.DAYS
        );
        return JSON.parseArray(trainPriceInfo, TrainStationPriceDO.class);
    }
}
